package com.woniuxy.tfss.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.tfss.entity.Order;
import com.woniuxy.tfss.entity.ResponseEntity;
import com.woniuxy.tfss.entity.Rider;
import com.woniuxy.tfss.entity.User;
import com.woniuxy.tfss.exception.NoAccountException;
import com.woniuxy.tfss.exception.PasswordWrongException;
import com.woniuxy.tfss.exception.RiderExistException;
import com.woniuxy.tfss.exception.ServiceException;
import com.woniuxy.tfss.service.InformationService;
import com.woniuxy.tfss.service.OrderService;
import com.woniuxy.tfss.service.RiderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("rider")
@CrossOrigin
public class RiderController {
    @Autowired
    private RiderService riderService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private InformationService informationService;

    @GetMapping("login")
    public String login(Model model) {
        model.addAttribute("rider", new Rider());
        return "riderLogin";
    }

    @GetMapping("logout")
    public String logout(HttpSession session) {
        session.removeAttribute("rider");
        return "redirect:/";
    }

    @PostMapping("login")
    public String login(Rider rider, Model model, HttpSession session) {
        String phoneNum=rider.getPhoneNum();
        String password = rider.getPassword();
        Rider rider1 = riderService.getByPhoneNum(phoneNum);//rider1用来向页面传递
        try {
            riderService.login(phoneNum, password);
            session.setAttribute("rider", rider1);
            return "redirect:/";
        } catch (ServiceException e) {
            if (e instanceof NoAccountException) {
                model.addAttribute("message1", "账号不存在！");
                return "riderLogin";
            } else if (e instanceof PasswordWrongException) {
                 model.addAttribute("message2", "密码错误！");
                return "riderLogin";
            } else {
                return "fail";
            }
        }
    }
    @GetMapping("reg")
    public String reg(Model model) {
        model.addAttribute("rider", new Rider());
        return "riderReg";
    }
    @PostMapping("reg")
    public String reg(@Validated Rider rider, Model model, HttpSession session, String putCheckcode){
        String password = rider.getPassword();
        String repassword=rider.getRpassword();
        String checkcode = (String) session.getAttribute("checkcode");
        //判断确认密码
        if (!password.equals(repassword)) {
            return "riderReg";
        }
        //判断短信验证码
        if (!putCheckcode.equals(checkcode)) {
            return "riderReg";
        }
        //根据手机号码或身份证号判断是否已存在
        try {
            riderService.reg(rider);
            return "riderLogin";
        }catch (ServiceException e){
            if (e instanceof NoAccountException){
                model.addAttribute("message1", "账号已存在！");
                return "riderReg";
            }else if (e instanceof RiderExistException){
                model.addAttribute("message2", "骑手已注册！");
                return "riderReg";
            }
        }
        return "riderReg";
    }
    @GetMapping("random")
    @ResponseBody
    public ResponseEntity<?> randomDispatch(){//系统随机派单(用户即时下单)
        QueryWrapper<Rider> wraaper1 = new QueryWrapper<>();
        wraaper1.eq("status", Rider.NORMAL);//选择工作中且等待状态的骑手
        wraaper1.eq("workStatus",Rider.WAIT);//选择未冻结的骑手
        List<Rider> riders=riderService.list(wraaper1);
        if(riders.size()==0){
            return ResponseEntity.NOACTIVERIDER;//没有合适状态的骑手(801)
        }
        double [][] weights=new double [riders.size()][1];
        riders.forEach(r->{
            for(int i=0;i<riders.size();i++){
                weights[i][0]=riders.get(i).getCredit();//产生所有骑手信用分的二维数组
            }
        });
        if( RandomByWeight(weights)!=-1){
            //System.out.println(riders.get(RandomByWeight(weights)).getId());
            return new ResponseEntity<>(riders.get(RandomByWeight(weights)).getId());//返回被派单骑手的id
        }
        return ResponseEntity.FAIL;//其他类型的派单失败
    }


    public static int RandomByWeight(double[][] weights) {//系统随机派单中按照权重分配的方法
        Random random = new Random();
        int weightSum = 0;
        for (int i = 0; i < weights.length; i++) {
            weightSum += weights[i][0]*10000;//10000是精度 值越大精度越高
        }
        int number_rand = random.nextInt(weightSum); //总的权重中生成一个随机数
        int sum_temp = 0;
        //循环数组 判断生成的随机数是否小于等于当前权重 是就返回序号,否则加上当前的权重继续循环(多次执行,增加精度)
        for (int i = 0; i < weights.length; i++) {
            sum_temp += weights[i][0]*10000;
            if (number_rand <= sum_temp) {
                return i;
            }
        }
        return -1;
    }


    /**
     * 骑手个人中心查询订单
     *
     * @param flag    标识变量，用于区别查询信息
     *                list--全部完成订单 today--今日完成订单 waitTake--未分配 Riding--配送中 Received--待评价 cancel--取消
     * @param session
     * @param model
     * @return
     */
    @GetMapping("{flag}")
    public String getTodayOrder(@PathVariable String flag, HttpSession session, Model model) {
        Rider rider = (Rider) session.getAttribute("rider");
        if (rider == null) {  
            model.addAttribute("rider", new Rider());
            return "riderLogin";
        }
        if (flag.equals("list")) {
            List<Order> orders = orderService.getByRiderId(rider.getId(),Order.REMARKED);
            model.addAttribute("orders", orders);
        }
        if (flag.equals("today")) {
            List<Order> orders = orderService.getRiderTodayOrder(rider.getId());
            model.addAttribute("orders", orders);
        }
        if (flag.equals("waitTake")) {
            List<Order> orders = orderService.getCanRobOrder();
            model.addAttribute("orders", orders);
        }
        if (flag.equals("riding")) {
            List<Order> orders = orderService.getByRiderId(rider.getId(), Order.RIDING);
            model.addAttribute("orders", orders);
        }
        if (flag.equals("received")) {
            List<Order> orders = orderService.getByRiderId(rider.getId(), Order.RECEIVED);
            model.addAttribute("orders", orders);
        }
        if (flag.equals("cancel")) {
            List<Order> orders = orderService.getByRiderId(rider.getId(), Order.CANCEL);
            model.addAttribute("orders", orders);
        }
        model.addAttribute("flag", flag);
        return "rider_orders";
    }

    @GetMapping("getInformations/{riderId}")
    @ResponseBody
    public ResponseEntity<?> getInformationsByRiderId(@PathVariable Integer riderId){//获取骑手的消息列表
        return new ResponseEntity<>(informationService.getByRiderId(riderId));
    }
    /**
     * 进入修改密码页面
     *
     * @return
     */
    @GetMapping("updatepwd")
    public String initUpdate() {
        return "rider_pwd";
    }

    /**
     * 修改密码
     *
     * @param session
     * @param newPassword
     * @param passwordRepeat
     * @return
     */
    @PostMapping("updatepwd")
    public String updatePwd(HttpSession session, String newPassword, String passwordRepeat,Model model) {
//判断确认密码是否一致
        if (!passwordRepeat.equals(newPassword)) {
            return "fail";
        }
        Rider rider = (Rider) session.getAttribute("rider");

        rider.setPassword(newPassword);
        riderService.updateById(rider);
        model.addAttribute("rider", new Rider());
        return "riderLogin";
    }

    /**
     * 收益与信用
     * @return
     */
    @GetMapping("balance")
    public String userAccount(HttpSession session,Model model){
        Rider rider = (Rider) session.getAttribute("rider");
        if(rider != null){
//            String phoneNum = rider.getPhoneNum();
//            BigDecimal money = riderService.getUserByPhoneNum(phoneNum).getMoney();
        //    model.addAttribute("money",money);
            return "rider_balance";
        }else{ //session过期或被清除--重新登录
            model.addAttribute("rider", new Rider());
            return "riderLogin";
        }
    }
}
